package com.myhouse.common.utils.myquartz.factory;

import com.myhouse.common.exception.MyException;
import com.myhouse.common.utils.myquartz.config.MyQuartzConfig;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.quartz.*;

import java.util.Date;
import java.util.Map;

/**
 * Trigger工厂（单例模式）
 * @author 章瑜亮
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TriggerFactory {
    /**
     * 生成实例
     * @param jobClass jobClass
     * @param triggerType triggerType
     * @param triggerName triggerName
     * @param triggerGroup triggerGroup
     * @param params params
     * @return jobDetail
     */
    public static Trigger getInstance(
            Class<? extends Job> jobClass,
            MyQuartzConfig triggerType,
            String triggerName,
            String triggerGroup,
            Map<String,Object> params
    ) {
        if (jobClass == null) {
            throw new MyException("任务为空");
        }
        if (triggerType == null) {
            throw new MyException("trigger 类型为空");
        }
        JobDataMap map = new JobDataMap();
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                map.put(entry.getKey(), entry.getValue());
            }
        }
        switch (triggerType.getMode()) {
            case "simple":
                SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule();
                //多少秒执行一次,默认180s
                if (triggerType.getDelay() == null) {
                    triggerType.setDelay(180);
                }
                scheduleBuilder.withIntervalInSeconds(triggerType.getDelay());
                //持续运行下去
                if (triggerType.getRepeatable().equalsIgnoreCase("true")) {
                    scheduleBuilder.repeatForever();
                }
                //立刻启动
                if (triggerType.getStartNow().equalsIgnoreCase("true")) {
                    return TriggerBuilder.newTrigger()
                            .withIdentity(triggerName,triggerGroup)
                            .startNow()
                            .withSchedule(scheduleBuilder)
                            .usingJobData(map)
                            .build();
                } else {
                    long currentTime = System.currentTimeMillis();
                    Date date = new Date(currentTime + triggerType.getDelay() * 1000);
                    return TriggerBuilder.newTrigger()
                            .withIdentity(triggerName,triggerGroup)
                            .startAt(date)
                            .withSchedule(scheduleBuilder)
                            .usingJobData(map)
                            .build();
                }
            case "cron":
                if (triggerType.getCron() == null || triggerType.getCron().isEmpty()) {
                    throw new MyException("cron表达式不存在");
                }
                return TriggerBuilder.newTrigger()
                        .withIdentity(triggerName,triggerGroup)
                        .withSchedule(CronScheduleBuilder.cronSchedule(triggerType.getCron()))
                        .usingJobData(map)
                        .build();
            default: throw new MyException("定时任务trigger类型有误，请检查");
        }
    }
}
